<script setup lang="ts">
import {
  NForm,
  NInput,
  NSelect,
  NButton,
  NFormItem,
  NDatePicker,
  NInputNumber,
  NTreeSelect,
  useMessage,
  NImage,
  NTooltip,
  type UploadFileInfo,
  type SelectOption
} from 'naive-ui'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { onMounted, ref, reactive } from 'vue'
import type { BatchDetailModel } from '@/api/batchV2'
import type { DicTreeModel } from '@/api/dic'
import type { HttpResponse } from '@/utils/http'
import useRouteReplace from '@/hooks/useRouteReplace'
import VBackImg from '@/assets/images/back.png'
import FixedAction from '@/components/FixedAction.vue'
import VAttachments from '@/views/OA/Common/Attachments.vue'
import BatchCres from './components/BatchCres.vue'
import BatchAttchDetail from './components/BatchAttchDetail.vue'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const message = useMessage()

const clueSelectOptions = ref<SelectOption[]>([])
const clueSelectLoading = ref(false)
const queryClueSelectOptions = async () => {
  clueSelectLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'batchV2',
      api: 'clueList'
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    clueSelectLoading.value = false
  }
}

const clueMethodOptions = reactive<DicTreeModel[]>([])
const clueMethodLoading = ref(false)
const queryClueMethodOptions = async () => {
  clueMethodLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: 'A30'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueMethodOptions.length = 0
    clueMethodOptions.push(...(res.data[0] ? res.data[0].children || [] : []))
  } catch (error) {
    console.error(error)
  } finally {
    clueMethodLoading.value = false
  }
}

const collectorName = ref<string | null>(null)

const batchInfo = ref({} as BatchDetailModel)
const queryBatchInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<BatchDetailModel>>({
    module: 'batchV2',
    api: 'detail',
    override: {
      params: {
        id: route.params.id
      }
    }
  })
  if (error) return message.error(error.message)

  sendRequest({
    module: 'clue',
    api: 'infoManage',
    uri: {
      id: res.data.clueId
    }
  })
    .then(([_, cr]) => {
      if (cr) {
        sendRequest({
          module: 'collector',
          api: 'info',
          uri: {
            id: cr.data.collectorId
          }
        })
          .then(([_, er]) => {
            if (er) collectorName.value = er.data.userName
          })
          .catch(() => (collectorName.value = null))
      }
    })
    .catch(() => (collectorName.value = null))

  if (res.data.endTime) {
    res.data.endTime = res.data.endTime.slice(0, 10)
  }
  if (res.data.startTime) {
    res.data.startTime = res.data.startTime.slice(0, 10)
  }
  if (res.data.solicitNum) {
    res.data.solicitNum = Number(res.data.solicitNum)
  }
  batchInfo.value = res.data
  if (res.data.fileIds) queryFileList(res.data.fileIds)
}

const fileList = ref<UploadFileInfo[]>([])
const queryFileList = async (filesIds: string) => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    fileList.value = res.data.map((e) => ({
      id: e.id,
      path: e.path,
      name: e.name,
      url: e.path,
      status: 'success'
    })) as unknown as UploadFileInfo[]
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  queryClueSelectOptions()
  queryClueMethodOptions()
  queryBatchInfo()
})
</script>

<template>
  <div class="batch-created-detail">
    <div class="bc-title">批次详情</div>
    <DetailFormProvider>
      <NForm
        disabled
        label-placement="left"
        label-width="100rem"
        :show-feedback="false"
        :show-require-mark="false"
        class="bc-card form"
      >
        <NFormItem label="关联线索：">
          <NSelect
            :value="batchInfo.clueId"
            :options="clueSelectOptions"
            :loading="clueSelectLoading"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="批次名称：">
          <NTooltip :max-width="350">
            <template #trigger>
              <NInput
                :value="batchInfo.name"
                placeholder="/"
              />
            </template>
            {{ batchInfo.name }}
          </NTooltip>
        </NFormItem>
        <NFormItem label="征集方式：">
          <NTreeSelect
            :value="batchInfo.solicitMethodCode"
            :options="clueMethodOptions"
            :loading="clueMethodLoading"
            placeholder="/"
            key-field="code"
            label-field="name"
          />
        </NFormItem>
        <NFormItem label="接收时间：">
          <NDatePicker
            :formatted-value="batchInfo.receiveTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="接收人：">
          <NInput
            :value="batchInfo.receiver"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="征集数量：">
          <NInputNumber
            :value="batchInfo.solicitNum"
            placeholder="/"
            :show-button="false"
            :min="0"
            :max="Number.MAX_SAFE_INTEGER"
          />
        </NFormItem>
        <NFormItem label="证书发放：">
          <BatchCres
            :batch-id="batchInfo.id"
            style="flex: 1"
          />
        </NFormItem>
        <template v-if="batchInfo.solicitMethodCode == 'A3007'">
          <NFormItem label="开始时间：">
            <NDatePicker
              :formatted-value="batchInfo.startTime"
              type="date"
              placeholder="/"
            />
          </NFormItem>
          <NFormItem label="结束时间：">
            <NDatePicker
              :formatted-value="batchInfo.endTime"
              type="date"
              placeholder="/"
            />
          </NFormItem>
          <NFormItem label="代存期限：">
            <NInput
              :value="batchInfo.depositPeriod"
              placeholder="/"
            />
          </NFormItem>
        </template>

        <NFormItem label="藏家：">
          <NInput
            v-model:value="collectorName"
            placeholder="/"
            disabled
          />
        </NFormItem>
        <NFormItem label="移交人：">
          <NInput
            v-model:value="batchInfo.transferor"
            placeholder="/"
            disabled
            style="flex-shrink: 2"
          />
          <NInput
            v-model:value="batchInfo.transferorPhone"
            placeholder="/"
            disabled
          />
        </NFormItem>

        <NFormItem label="创建时间：">
          <NDatePicker
            :formatted-value="batchInfo.createTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="修改时间：">
          <NDatePicker
            :formatted-value="batchInfo.modifyTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="鉴定状态：">
          <NInput
            :value="batchInfo.identifyStatus"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem
          label="备注："
          class="n-form-item--textarea"
        >
          <NInput
            :value="batchInfo.remark"
            type="textarea"
            placeholder="/"
            rows="5"
          />
        </NFormItem>

        <NFormItem label="附件：">
          <VAttachments
            v-if="batchInfo.fileIds"
            :attach-list="fileList"
          />
        </NFormItem>
      </NForm>
    </DetailFormProvider>

    <BatchAttchDetail />
  </div>
  <FixedAction>
    <div class="common-buttons">
      <NButton
        ghost
        @click="routeReplace"
        :style="`width: 78px; color: #5fb17f`"
      >
        <template #icon>
          <NImage
            :src="VBackImg"
            :style="`width: 50rem; height: 50rem`"
            preview-disabled
          ></NImage>
        </template>
        返回
      </NButton>
    </div>
  </FixedAction>
</template>

<style lang="scss" scoped>
.batch-created-detail {
  min-height: 100%;
  padding: 15rem 0 130rem;
  background-color: #f0efee;
}

.bc-title {
  font-size: 26rem;
  margin-bottom: 30rem;
  color: #048c5e;
  line-height: 1;
}

.bc-card {
  padding: 26rem 20rem;
  background-color: #e1e1e1;

  &.form {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 26rem 32rem;

    .n-form-item--textarea {
      grid-column: 1 / -1;
    }

    .n-date-picker,
    .n-input-number {
      flex: 1;
    }
  }
}

.common-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>
